<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">

      <!-- <el-form-item label="日期" prop="recordDate">
        <el-date-picker clearable v-model="queryParams.recordDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="借(用)款人" prop="borrowDebit">
        <el-input v-model="queryParams.borrowDebit" placeholder="请输入借(用)款人" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="支出" prop="expenditure">
        <el-input v-model="queryParams.expenditure" placeholder="请输入支出" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="借款" prop="borrowCredit">
        <el-input v-model="queryParams.borrowCredit" placeholder="请输入借款" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="所属项目" prop="projectId">
        <el-select clearable filterable v-model="queryParams.projectId" placeholder="请选择项目">
          <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="资金用途" prop="fundPurpose">
        <el-select v-model="queryParams.fundPurpose" placeholder="请选择资金用途" clearable filterable>
          <el-option v-for="dict in dict.type.fund_use" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="申请状态" prop="applicationStatus">
        <el-select v-model="queryParams.applicationStatus" placeholder="请选择申请状态" clearable filterable>
          <el-option v-for="dict in dict.type.review_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['cost:prodProjectFund:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['cost:prodProjectFund:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['cost:prodProjectFund:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['cost:prodProjectFund:add']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['cost:prodProjectFund:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 颜色说明 -->
    <div class="color-legend" style="margin-bottom: 10px; font-size: 12px; color: #666;">
      <!-- <div style="margin-bottom: 8px; font-weight: bold; color: #333;">注意：以下颜色标识仅适用于未审核状态的记录</div> -->
      <span style="margin-right: 15px;">
        <span
          style="display: inline-block; width: 16px; height: 16px; background-color: #fff3cd; border: 1px solid #ddd; margin-right: 5px;"></span>
        黄色：创建时间与日期相差超过3天且未审核
      </span>
      <span>
        <span
          style="display: inline-block; width: 16px; height: 16px; background-color: #f8d7da; border: 1px solid #ddd; margin-right: 5px;"></span>
        红色：创建时间与日期相差超过7天且未审核
      </span>
    </div>

    <el-table v-loading="loading" :data="prodProjectFundList" @selection-change="handleSelectionChange"
      :row-class-name="rowClassName">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="日期" align="center" prop="recordDate" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordDate) }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="所属项目" align="center" prop="projectId">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="getProjectNameById(scope.row.projectId)" placement="top">
            <span
              style="max-width: 400px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle;"
              :title="getProjectNameById(scope.row.projectId)">
              {{ getProjectNameById(scope.row.projectId) }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="资金类型" width="90" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.borrowCredit" type="primary" size="mini">借款</el-tag>
          <el-tag v-else-if="scope.row.expenditure" type="success" size="mini">支出</el-tag>
          <el-tag v-else size="mini">-</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="资金用途" width="100" align="center" prop="fundPurpose">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fund_use" :value="scope.row.fundPurpose" />
        </template>
      </el-table-column>
      <el-table-column label="金额" width="120" align="center" prop="borrowCredit,expenditure">
        <template slot-scope="scope">
          <span>{{ scope.row.borrowCredit ? '+' + scope.row.borrowCredit.toFixed(2) : '-' +
            scope.row.expenditure.toFixed(2)
          }}
            元</span>

        </template>
      </el-table-column>
      <!-- 
      <el-table-column label="借(用)款人" align="center" prop="borrowDebit" />
      <el-table-column label="借款" align="center" prop="borrowCredit" />
      
      <el-table-column label="支出" align="center" prop="expenditure" /> -->
      <el-table-column label="备注" align="center" prop="remark" width="250">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.remark || ''" placement="top">
            <span
              style="max-width: 230px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle;"
              :title="scope.row.remark || ''">
              {{ scope.row.remark || '-' }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" width="90" align="center" prop="applicationStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.review_status" :value="scope.row.applicationStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 审核按钮 -->
          <el-button v-if="scope.row.applicationStatus == 1" v-hasPermi="['cost:prodProjectFund:audit']" size="mini"
            type="text" icon="el-icon-check" @click="handleAudit(scope.row)">审核</el-button>

          <!-- 取消审核按钮 -->
          <el-button v-else-if="scope.row.applicationStatus == 2" v-hasPermi="['cost:prodProjectFund:unaudit']"
            size="mini" type="text" icon="el-icon-close" @click="handleCancelAudit(scope.row)">取消审核</el-button>

          <!-- 修改按钮 -->
          <el-button v-if="scope.row.applicationStatus == 1" v-hasPermi="['cost:prodProjectFund:edit']" size="mini"
            type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>

          <!-- 详情按钮 -->
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>

          <!-- 删除按钮 -->
          <el-button v-if="scope.row.applicationStatus == 1" v-hasPermi="['cost:prodProjectFund:remove']" size="mini"
            type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改项目资金台账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" style="width: 100%" filterable clearable
                @change="handleProjectChange">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="项目备用金余额">
              <span style="color: #409EFF; font-weight: bold; font-size: 16px;">
                {{ projectBalance > 0 ? '' : '' }}{{ projectBalance.toFixed(2) }} 元
              </span>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item :label="form.fundType === 'borrow' ? '项目累计借款' : '项目累计支出'">
              <span style="color: #67C23A; font-weight: bold; font-size: 16px;">
                {{ form.fundType === 'borrow' ? totalBorrow.toFixed(2) : totalExpenditure.toFixed(2) }} 元
              </span>
            </el-form-item>
          </el-col> -->
          <el-col :span="7">
            <el-form-item label="项目累计借款">
              <span style="color: red; font-weight: bold; font-size: 16px;">
                {{ totalBorrow.toFixed(2) }} 元
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="项目累计支出">
              <span style="color: #67C23A; font-weight: bold; font-size: 16px;">
                {{ totalExpenditure.toFixed(2) }} 元
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="日期" prop="recordDate">
              <el-date-picker v-model="form.recordDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                placeholder="请选择日期" style="width: 100%" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型选择" prop="fundType">
              <el-select v-model="form.fundType" placeholder="请选择类型" style="width: 100%" @change="handleFundTypeChange"
                :disabled="!!form.id">
                <el-option label="借款" value="borrow" />
                <el-option label="支出" value="expenditure" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="form.fundType === 'borrow'">
          <el-col :span="12">
            <el-form-item label="借款人" prop="borrowDebit">
              <el-input v-model="form.borrowDebit" placeholder="请输入借(用)款人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本次借款" prop="borrowCredit">
              <el-input v-model="form.borrowCredit" placeholder="请输入借款" @input="handleBorrowInput" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="form.fundType === 'expenditure'">
          <el-col :span="12">
            <el-form-item label="资金用途" prop="fundPurpose">
              <el-select v-model="form.fundPurpose" placeholder="请选择资金用途" filterable style="width: 100%">
                <el-option v-for="dict in dict.type.fund_use" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本次支出" prop="expenditure">
              <el-input v-model="form.expenditure" placeholder="请输入支出" @input="handleExpenditureInput" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="上传凭证" class="upload-form-item">
          <div class="upload-container">
            <el-upload ref="upload" drag action="#" :auto-upload="true" :multiple="true" list-type="picture-card"
              :on-change="onUploadChange" :on-remove="onUploadRemove" :on-exceed="onUploadExceed"
              :file-list="uploadFileList" accept="image/*" class="upload-component" :http-request="handleCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">仅用于随单据上传的图片凭证，支持多张</div>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="上传文件" class="upload-form-item">
          <div class="upload-container">
            <el-upload ref="fileUpload" drag action="#" :auto-upload="true" list-type="text"
              :on-change="onFileUploadChange" :on-remove="onFileUploadRemove" :on-exceed="onFileUploadExceed"
              :file-list="uploadDocumentList" accept=".pdf,.doc,.docx" class="file-upload-component"
              :http-request="handleFileCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                仅支持PDF和Word文件，支持多个文件
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="detailOpen" width="900px" :show-close="true" append-to-body class="daily-detail-dialog">
      <div class="daily-detail-title">项目资金台账详情</div>
      <div class="daily-section-title">基本信息</div>
      <div class="daily-row-flex">
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">所属项目</th>
              <td class="value">{{ getProjectNameById(detailForm.projectId) }}</td>
            </tr>
            <tr>
              <th class="left-align">日期</th>
              <td class="value">{{ detailForm.recordDate }}</td>
            </tr>
            <tr v-if="Number(detailForm.borrowCredit) > 0">
              <th class="left-align">借款</th>
              <td class="value">{{ detailForm.borrowCredit }}</td>
            </tr>
            <tr v-if="Number(detailForm.expenditure) > 0">
              <th class="left-align">支出</th>
              <td class="value">{{ detailForm.expenditure }}</td>
            </tr>
          </table>
        </div>
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">申请状态</th>
              <td class="value"><dict-tag :options="dict.type.review_status" :value="detailForm.applicationStatus" />
              </td>
            </tr>
            <tr v-if="Number(detailForm.expenditure) > 0">
              <th class="left-align">资金用途</th>
              <td class="value"><dict-tag :options="dict.type.fund_use" :value="detailForm.fundPurpose" /></td>
            </tr>
            <tr v-if="Number(detailForm.borrowCredit) > 0">
              <th class="left-align">借款人</th>
              <td class="value">{{ detailForm.borrowDebit }}</td>
            </tr>


            <tr>
              <th class="left-align">备注</th>
              <td class="value">{{ detailForm.remark }}</td>
            </tr>
          </table>
        </div>
      </div>

      <!-- 凭证信息 -->
      <!-- <div class="daily-section-title">凭证信息</div>
      <div class="daily-row-flex">
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">凭证数量</th>
              <td class="value">{{ detailImageUrls.length }} 张</td>
            </tr>
            <tr v-if="detailForm.imageList && detailForm.imageList.length > 0">
              <th class="left-align">原始链接</th>
              <td class="value">
                <div v-for="(url, index) in detailForm.imageList" :key="`original-${index}`"
                  style="font-size: 12px; color: #666; margin-bottom: 4px; word-break: break-all;">
                  {{ index + 1 }}. {{ url }}
                </div>
              </td>
            </tr>
          </table>
        </div>
      </div> -->

      <!-- 图片展示区域 -->
      <div class="daily-section-title">凭证信息</div>
      <div v-if="detailImageUrls && detailImageUrls.length > 0" class="image-display-container">
        <div v-for="(url, index) in detailImageUrls" :key="`display-${index}`" class="image-item">
          <el-image :src="url" :preview-src-list="detailImageUrls" fit="cover" class="detail-image">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </div>
      </div>

      <!-- 文件展示区域 -->
      <div v-if="detailFileList && detailFileList.length > 0" class="daily-section-title">附件信息</div>
      <div v-if="detailFileList && detailFileList.length > 0" class="file-display-container">
        <div v-for="(file, index) in detailFileList" :key="`file-${index}`" class="file-item">
          <div class="file-info">
            <i class="el-icon-document"></i>
            <span class="file-name">{{ file.fileName }}</span>
            <div class="file-actions">
              <el-button type="primary" size="mini" icon="el-icon-download" @click="handleFileDownload(file)">
                下载
              </el-button>
              <el-button type="success" size="mini" icon="el-icon-view" @click="handleFilePreview(file)">
                预览
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false" type="primary" plain>关闭</el-button>
      </span>
    </el-dialog>

    <!-- 文件预览弹框 -->
    <el-dialog :visible.sync="previewDialogVisible" width="60vw" top="5vh" :title="getPreviewTitle()"
      @close="previewFile = null">
      <div v-if="previewFile">
        <!-- 图片预览 -->
        <el-image v-if="getFileType(previewFile.fileName) === 'image'" :src="previewFile.downloadUrl"
          :preview-src-list="[previewFile.downloadUrl]" fit="contain"
          style="max-width:100%;max-height:70vh;display:block;margin:auto;cursor:pointer;">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        <!-- 文档/PDF/Word/Excel 预览：直接用iframe打开 -->
        <iframe v-else-if="['pdf', 'word', 'excel', 'ppt'].includes(getFileType(previewFile.fileName))"
          :src="previewFile.downloadUrl" style="width:100%;height:70vh;border:none;"></iframe>
        <!-- 其他类型提示 -->
        <div v-else style="text-align:center;padding:40px 0;color:#888;">
          暂不支持该类型文件的在线预览，请下载后查看。
        </div>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog title="导入项目资金台账" :visible.sync="importOpen" width="500px" append-to-body>
      <el-form ref="importForm" :model="importForm" :rules="importRules" label-width="100px">
        <el-form-item label="所属项目" prop="porjectId">
          <el-select v-model="importForm.porjectId" placeholder="请选择所属项目" style="width: 100%">
            <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件" prop="file">
          <el-upload ref="upload" :limit="1" accept=".xlsx,.xls" :headers="upload.headers" :action="upload.url"
            :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
            :on-change="handleFileChange" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false"
                style="font-size:12px;vertical-align: baseline; margin-left: 8px;"
                @click="importTemplate">下载模板</el-link>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport" :loading="upload.isUploading">确 定</el-button>
        <el-button @click="cancelImport">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProdProjectFund, getProdProjectFund, delProdProjectFund, addProdProjectFund, updateProdProjectFund, getProdProjectAllCoast, addImg, delImg, prodProjectFundFileImport } from "@/api/cost/prodProjectFund";
import { listAllProjectContractInfo } from '@/api/production/projectContractInfo';
import { fileLinkTransfer, fileLinkLooking } from "@/api/production/projectFileInfo";
export default {
  name: "ProdProjectFund",
  dicts: ['fund_use', 'review_status'],
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目资金台账表格数据
      prodProjectFundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        recordDate: null,
        borrowDebit: null,
        borrowCredit: null,
        fundPurpose: null,
        expenditure: null,
        remark: null,
        applicationStatus: null,
      },
      // 表单参数
      form: {
        fundType: 'borrow', // 默认选中借款
        imageList: [], // 存储转换后的图片链接数组
      },
      // 项目资金余额
      projectBalance: 0,
      // 原始项目资金余额（不包含当前输入）
      originalProjectBalance: 0,
      // 项目总借款
      totalBorrow: 0,
      // 项目总支出
      totalExpenditure: 0,
      // 详情弹窗
      detailOpen: false,
      detailForm: {},
      // 详情页面的图片链接
      detailImageUrls: [],
      // 详情页面的文件列表
      detailFileList: [],
      // 文件预览相关
      previewDialogVisible: false,
      previewFile: null,
      // 处理后的图片链接（用于回显）
      processedImageList: [],
      // 上传文件列表（图片）
      uploadFileList: [],
      // 上传文件列表（文档）
      uploadDocumentList: [],
      // 项目选项
      projectOptions: [],
      // 导入相关
      importOpen: false,
      importForm: { porjectId: null, file: null },
      importRules: {
        porjectId: [{ required: true, message: "请选择所属项目", trigger: "change" }],
        file: [{ required: true, message: "请选择要导入的文件", trigger: "change" }]
      },
      upload: {
        isUploading: false,
        headers: {},
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键ID不能为空", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "所属项目不能为空", trigger: "change" }
        ],
        recordDate: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        fundType: [
          { required: true, message: "类型选择不能为空", trigger: "change" }
        ],
        borrowDebit: [
          {
            required: true,
            message: "借(用)款人不能为空",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.form.fundType === 'borrow' && !value) {
                callback(new Error('借(用)款人不能为空'));
              } else {
                callback();
              }
            }
          }
        ],
        borrowCredit: [
          {
            required: true,
            message: "借款不能为空",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.form.fundType === 'borrow' && !value) {
                callback(new Error('借款不能为空'));
              } else {
                callback();
              }
            }
          }
        ],
        fundPurpose: [
          {
            required: true,
            message: "资金用途不能为空",
            trigger: "change",
            validator: (rule, value, callback) => {
              if (this.form.fundType === 'expenditure' && !value) {
                callback(new Error('资金用途不能为空'));
              } else {
                callback();
              }
            }
          }
        ],
        expenditure: [
          {
            required: true,
            message: "支出不能为空",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.form.fundType === 'expenditure' && !value) {
                callback(new Error('支出不能为空'));
              } else {
                callback();
              }
            }
          }
        ],
        // remark: [
        //   { required: true, message: "备注不能为空", trigger: "blur" }
        // ],
        applicationStatus: [
          { required: true, message: "申请状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.fetchProjectOptions();
    // 设置上传请求头
    this.upload.headers = { Authorization: "Bearer " + this.$store.getters.token };
  },
  methods: {
    /** 查询项目资金台账列表 */
    getList() {
      this.loading = true;
      listProdProjectFund(this.queryParams).then(response => {
        this.prodProjectFundList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        recordDate: null,
        fundType: 'borrow', // 默认选中借款
        borrowDebit: null,
        borrowCredit: null,
        fundPurpose: null,
        expenditure: null,
        remark: null,
        applicationStatus: 1,
        entryTime: null,
        imageList: [], // 重置图片链接数组
      };
      this.uploadFileList = [];
      this.uploadDocumentList = []; // 重置文档上传列表
      this.processedImageList = []; // 重置处理后的图片链接
      this.projectBalance = 0; // 重置项目余额
      this.originalProjectBalance = 0; // 重置原始余额
      this.totalBorrow = 0; // 重置总借款
      this.totalExpenditure = 0; // 重置总支出
      this.resetForm("form");
    },
    onUploadChange(file, fileList) {
      this.uploadFileList = fileList;
    },
    // 自定义上传：调用 addImg 接口将文件转为图片链接
    async handleCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error('无可上传文件'));
        return;
      }

      try {
        // 上传文件并获取原始路径
        const { msg: filePath } = await addImg(file);
        if (!filePath) {
          throw new Error('未获取到文件路径');
        }

        // 获取可访问链接
        const { data: { url } } = await fileLinkTransfer(filePath);
        if (!url) {
          throw new Error('未获取到可访问的图片链接');
        }

        // 创建文件项，保存原始路径用于删除
        const fileItem = {
          name: file.name || 'image.jpg',
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath, // 保存原始路径
        };

        // 更新文件列表和表单数据
        this.uploadFileList = [...this.uploadFileList, fileItem];
        this.form.imageList.push(filePath);

        // 调用成功回调
        param?.onSuccess?.({ url });

      } catch (err) {
        this.$message.error('图片上传失败');
        param?.onError?.(err);
      }
    },
    // 删除图片：仅本地移除，不调用后端
    async onUploadRemove(file, fileList) {
      const { url } = file || {};
      if (!url) {
        this.uploadFileList = fileList;
        return;
      }

      // 找到对应的文件项，获取原始路径，仅更新本地数组
      const fileItem = this.uploadFileList.find((item) => item.url === url);
      if (fileItem && fileItem.originalPath) {
        const originalPath = fileItem.originalPath;
        const imageListIndex = this.form.imageList.indexOf(originalPath);
        if (imageListIndex > -1) {
          this.form.imageList.splice(imageListIndex, 1);
        }
      }
      this.uploadFileList = fileList;
    },
    onUploadExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${fileList.length} 张图片，已选择 ${files.length} 张`);
    },
    // 文件上传相关方法
    onFileUploadChange(file, fileList) {
      this.uploadDocumentList = fileList;
    },
    // 自定义文件上传：调用 addImg 接口将文件转为文件链接
    async handleFileCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error("无可上传文件"));
        return;
      }

      // 检查文件类型
      const allowedTypes = ['.pdf', '.doc', '.docx'];
      const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
      if (!allowedTypes.includes(fileExtension)) {
        this.$message.error("只支持PDF和Word文件");
        param?.onError?.(new Error("文件类型不支持"));
        return;
      }

      try {
        // 上传文件并获取原始路径
        const { msg: filePath } = await addImg(file);
        if (!filePath) {
          throw new Error("未获取到文件路径");
        }

        // 获取可访问链接
        const {
          data: { url },
        } = await fileLinkTransfer(filePath);
        if (!url) {
          throw new Error("未获取到可访问的文件链接");
        }

        // 创建文件项，保存原始路径用于删除
        const fileItem = {
          name: file.name || "document.pdf",
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath, // 保存原始路径
        };

        // 更新文件列表和表单数据
        this.uploadDocumentList = [...this.uploadDocumentList, fileItem];
        this.form.imageList.push(filePath);

        // 调用成功回调
        param?.onSuccess?.({ url });
      } catch (err) {
        this.$message.error("文件上传失败");
        param?.onError?.(err);
      }
    },
    // 删除文件：仅本地移除，不调用后端
    async onFileUploadRemove(file, fileList) {
      const { url } = file || {};
      if (!url) {
        this.uploadDocumentList = fileList;
        return;
      }

      // 找到对应的文件项，获取原始路径，仅更新本地数组
      const fileItem = this.uploadDocumentList.find((item) => item.url === url);
      if (fileItem && fileItem.originalPath) {
        const originalPath = fileItem.originalPath;
        const imageListIndex = this.form.imageList.indexOf(originalPath);
        if (imageListIndex > -1) {
          this.form.imageList.splice(imageListIndex, 1);
        }
      }
      this.uploadDocumentList = fileList;
    },
    onFileUploadExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${fileList.length} 个文件，已选择 ${files.length} 个`
      );
    },
    /** 获取项目选项 */
    async fetchProjectOptions() {
      try {
        const { data } = await listAllProjectContractInfo();
        this.projectOptions = data || [];
      } catch (error) {
        this.$message.error('获取项目列表失败');
      }
    },
    /** 根据项目ID获取项目名称 */
    getProjectNameById(projectId) {
      const name = this.projectOptions.find(p => p.id == projectId)?.projectName;
      return String(name ?? (projectId ?? ''));
    },
    /** 处理资金类型变化 */
    handleFundTypeChange(value) {
      if (value === 'borrow') {
        this.form.fundPurpose = null;
        this.form.expenditure = null;
      } else if (value === 'expenditure') {
        this.form.borrowDebit = null;
        this.form.borrowCredit = null;
      }
      // 恢复原始余额
      this.projectBalance = this.originalProjectBalance;
    },
    /** 处理项目选择变化 */
    async handleProjectChange(projectId) {
      if (!projectId) {
        this.resetProjectBalance();
        return;
      }

      try {
        const { data } = await getProdProjectAllCoast(projectId);
        if (data) {
          const totalBorrow = parseFloat(data.totalBorrow) || 0;
          const totalExpenditure = parseFloat(data.totalExpenditure) || 0;
          const balance = totalBorrow - totalExpenditure;

          this.originalProjectBalance = balance;
          this.projectBalance = balance;
          this.totalBorrow = totalBorrow;
          this.totalExpenditure = totalExpenditure;
        }
      } catch (error) {
        this.$message.error('获取项目成本信息失败');
        this.resetProjectBalance();
      }
    },
    /** 获取原始余额 */
    getOriginalBalance() {
      return this.originalProjectBalance || 0;
    },
    /** 处理借款输入 */
    handleBorrowInput(value) {
      const borrowAmount = parseFloat(value) || 0;
      this.projectBalance = this.getOriginalBalance() + borrowAmount;
    },
    /** 处理支出输入 */
    handleExpenditureInput(value) {
      const expenditureAmount = parseFloat(value) || 0;
      const newBalance = this.getOriginalBalance() - expenditureAmount;
      this.projectBalance = newBalance;

      // 如果支出超过余额，显示警告
      if (newBalance < 0) {
        this.$message.warning(`支出金额 ${expenditureAmount} 元将导致余额不足，预计余额: ${newBalance.toFixed(2)} 元`);
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目资金台账";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      try {
        const { data } = await getProdProjectFund(id);
        this.form = data;
        console.log('修改 - 获取到的数据:', this.form);

        // 根据数据判断资金类型
        this.form.fundType = this.form.borrowCredit && this.form.borrowDebit ? 'borrow' :
          this.form.expenditure && this.form.fundPurpose ? 'expenditure' : 'borrow';

        // 处理图片回显
        console.log('修改 - 开始处理图片回显');
        await this.processImageListForDisplay();
        console.log('修改 - 处理后的 uploadFileList:', this.uploadFileList);

        this.open = true;
        this.title = "修改项目资金台账";
      } catch (error) {
        console.error('修改 - 获取数据失败:', error);
        this.$message.error('获取数据失败');
      }
    },
    /** 提交按钮 */
    async submitForm() {
      const valid = await this.$refs["form"].validate();
      if (!valid) return;

      try {
        if (this.form.id != null) {
          await updateProdProjectFund(this.form);
          this.$modal.msgSuccess("修改成功");
        } else {
          // 新增默认未审核，并自动添加录入时间
          this.form.applicationStatus = 1;
          this.form.entryTime = this.parseTime(new Date());

          const payload = { ...this.form, files: this.uploadFileList };
          await addProdProjectFund(payload);
          this.$modal.msgSuccess("新增成功");
        }

        this.open = false;
        this.getList();
      } catch (error) {
        this.$message.error('操作失败');
      }
    },
    async handleDetail(row) {
      try {
        const { data } = await getProdProjectFund(row.id);
        this.detailForm = data || {};
        console.log('详情 - 获取到的数据:', this.detailForm);

        // 处理图片和文件链接转换
        await this.processDetailImageAndFiles();

        this.detailOpen = true;
      } catch (error) {
        console.error('详情 - 获取详情失败:', error);
        this.$message.error('获取详情失败');
      }
    },
    async handleAudit(row) {
      try {
        await updateProdProjectFund({ ...row, applicationStatus: 2, clickAudit: true });
        this.$modal.msgSuccess('审核成功');
        this.getList();
      } catch (error) {
        this.$message.error('审核失败');
      }
    },

    async handleCancelAudit(row) {
      try {
        await updateProdProjectFund({ ...row, applicationStatus: 1, clickAudit: true });
        this.$modal.msgSuccess('已取消审核');
        this.getList();
      } catch (error) {
        this.$message.error('取消审核失败');
      }
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const ids = row.id || this.ids;

      try {
        await this.$modal.confirm('是否确认删除？');
        await delProdProjectFund(ids);
        this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch (error) {
        // 用户取消删除或删除失败时静默处理
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cost/prodProjectFund/export', {
        ...this.queryParams
      }, `prodProjectFund_${new Date().getTime()}.xlsx`)
    },
    /** 表格行样式 */
    rowClassName({ row }) {
      // 只有当申请状态为未审核(1)时才显示颜色
      if (row.applicationStatus !== 1) {
        return '';
      }

      // 计算录入时间与日期的差值
      const entry = this.parseDate(row.entryTime, true);
      const record = this.parseDate(row.recordDate);

      // 检查日期数据是否存在
      if (!entry || !record) {
        return '';
      }

      const diffDays = Math.floor((entry.getTime() - record.getTime()) / 86400000);

      if (diffDays > 7) {
        return 'over-seven-days';
      }
      if (diffDays > 3) {
        return 'over-three-days';
      }
      return '';
    },

    // 兼容多种日期字符串格式的解析，特别处理ISO 8601格式
    parseDate(val, isEntryTime = false) {
      if (!val) return null;
      if (val instanceof Date) return isNaN(val.getTime()) ? null : val;
      if (typeof val !== 'string') return null;

      let s = val.trim();

      // 如果是entryTime字段，只取前面的年月日部分
      if (isEntryTime && s.includes('T')) {
        const dateOnly = s.substring(0, 10);
        const d = new Date(dateOnly);
        if (!isNaN(d.getTime())) return d;
      }

      // 优先处理ISO 8601格式："2025-08-08T10:53:29.000+08:00"
      if (s.includes('T') && (s.includes('+') || s.includes('Z'))) {
        const d = new Date(s);
        if (!isNaN(d.getTime())) return d;
      }

      // 处理其他格式
      s = s.replace('T', ' ').replace(/-/g, '/');
      const d = new Date(s);
      if (!isNaN(d.getTime())) return d;

      // 退化为仅日期部分
      const onlyDate = s.slice(0, 10);
      const d2 = new Date(onlyDate);
      return isNaN(d2.getTime()) ? null : d2;
    },
    // 获取可访问的图片链接（用于显示）
    async getDisplayImageUrl(url) {
      console.log('getDisplayImageUrl - 输入:', url);

      if (!url) {
        console.log('getDisplayImageUrl - 空URL，返回空字符串');
        return '';
      }

      // 如果已经是完整的URL，直接返回
      // if (url.startsWith('http://') || url.startsWith('https://')) {
      //   console.log('getDisplayImageUrl - 已经是完整URL，直接返回:', url);
      //   return url;
      // }

      // 调用fileLinkTransfer获取可访问链接
      // try {
      console.log('getDisplayImageUrl - 调用 fileLinkTransfer:', url);
      const { data: { url: accessibleUrl } } = await fileLinkTransfer(url);
      console.log('getDisplayImageUrl - fileLinkTransfer 返回:', accessibleUrl);
      return accessibleUrl || url;
      // } catch (error) {
      //   console.error('getDisplayImageUrl - 转换失败:', error);
      //   return url;
      // }
    },
    // 获取图片链接列表（用于显示）
    async getDisplayImageUrlList(urls) {
      if (!Array.isArray(urls) || urls.length === 0) return [];

      return Promise.all(urls.map(url => this.getDisplayImageUrl(url)));
    },

    // 处理图片列表用于显示
    async processImageListForDisplay() {
      if (!this.form.imageList?.length) {
        this.form.imageList = [];
        this.uploadFileList = [];
        this.uploadDocumentList = [];
        return;
      }

      this.uploadFileList = [];
      this.uploadDocumentList = [];

      for (let i = 0; i < this.form.imageList.length; i++) {
        const url = this.form.imageList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            // 图片文件，添加到图片上传列表，保存原始路径用于删除
            this.uploadFileList.push({
              name: fileName || `image_${i + 1}.jpg`,
              url: displayUrl,
              uid: `existing_image_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          } else {
            // 文档文件，添加到文件上传列表，保存原始路径用于删除
            this.uploadDocumentList.push({
              name: fileName || `document_${i + 1}`,
              url: displayUrl,
              uid: `existing_file_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          }
        } catch (error) {
          console.error(`processImageListForDisplay - 转换失败:`, error);
          // 转换失败时，根据文件名判断类型
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            this.uploadFileList.push({
              name: fileName || `image_${i + 1}.jpg`,
              url,
              uid: `existing_image_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          } else {
            this.uploadDocumentList.push({
              name: fileName || `document_${i + 1}`,
              url,
              uid: `existing_file_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          }
        }
      }
    },

    // 重置项目余额
    resetProjectBalance() {
      this.originalProjectBalance = 0;
      this.projectBalance = 0;
      this.totalBorrow = 0;
      this.totalExpenditure = 0;
    }
    ,
    // 导入：打开/取消/重置
    handleImport() {
      this.importOpen = true;
      this.resetImport();
    },
    cancelImport() {
      this.importOpen = false;
      this.resetImport();
    },
    resetImport() {
      this.importForm = { porjectId: null, file: null };
      if (this.$refs.upload) this.$refs.upload.clearFiles();
      this.resetForm('importForm');
    },
    handleFileUploadProgress() {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file) {
      this.upload.isUploading = false;
      this.importForm.file = file;
    },
    handleFileChange(file) {
      this.importForm.file = file;
    },
    submitImport() {
      this.$refs['importForm'].validate(valid => {
        if (!valid) return;
        if (!this.importForm.file && (!this.$refs.upload || !this.$refs.upload.uploadFiles.length)) {
          this.$modal.msgError('请选择要导入的文件');
          return;
        }
        const file = this.importForm.file || (this.$refs.upload ? this.$refs.upload.uploadFiles[0] : null);
        if (!file) {
          this.$modal.msgError('请选择要导入的文件');
          return;
        }
        this.upload.isUploading = true;
        prodProjectFundFileImport(file, this.importForm.porjectId).then(() => {
          this.$modal.msgSuccess('导入成功');
          this.importOpen = false;
          this.resetImport();
          this.getList();
        }).catch(() => {
          this.upload.isUploading = false;
        });
      });
    },
    importTemplate() {
      const url = 'https://ggkt-1319488159.cos.ap-beijing.myqcloud.com/%E6%88%90%E6%9C%AC%E7%AE%A1%E7%90%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88/%E9%A1%B9%E7%9B%AE%E8%B5%84%E9%87%91%E5%8F%B0%E8%B4%A6%E5%AF%BC%E5%87%BA%E6%A8%A1%E7%89%88.xlsx';
      window.open(url, '_blank');
    },
    // 处理详情页面的图片和文件
    async processDetailImageAndFiles() {
      if (!this.detailForm.imageList?.length) {
        this.detailImageUrls = [];
        this.detailFileList = [];
        return;
      }

      this.detailImageUrls = [];
      this.detailFileList = [];

      for (let i = 0; i < this.detailForm.imageList.length; i++) {
        const url = this.detailForm.imageList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            // 图片文件
            this.detailImageUrls.push(displayUrl);
          } else {
            // 文档文件
            this.detailFileList.push({
              fileName: fileName,
              downloadUrl: url,
              displayUrl: displayUrl,
              fileType: fileType
            });
          }
        } catch (error) {
          console.error(`处理文件失败:`, error);
        }
      }
    },
    // 获取文件类型
    getFileType(fileName) {
      if (!fileName) return 'unknown';
      const extension = fileName.split('.').pop().toLowerCase();
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
      const pdfTypes = ['pdf'];
      const wordTypes = ['doc', 'docx'];
      const excelTypes = ['xls', 'xlsx'];
      const pptTypes = ['ppt', 'pptx'];

      if (imageTypes.includes(extension)) return 'image';
      if (pdfTypes.includes(extension)) return 'pdf';
      if (wordTypes.includes(extension)) return 'word';
      if (excelTypes.includes(extension)) return 'excel';
      if (pptTypes.includes(extension)) return 'ppt';
      return 'unknown';
    },
    // 判断是否为图片文件
    isImageFile(fileType) {
      return fileType === 'image';
    },
    // 从URL中提取文件名
    getFileNameFromUrl(url) {
      if (!url) return 'unknown';
      const parts = url.split('/');
      return parts[parts.length - 1] || 'unknown';
    },
    // 文件下载
    async handleFileDownload(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的下载链接");
        return;
      }
      try {
        const res = await fileLinkTransfer(file.downloadUrl);
        const newUrl = res.data.url;
        if (!newUrl) {
          this.$message.error("获取下载链接失败");
          return;
        }
        // 创建a标签下载
        const a = document.createElement("a");
        a.href = newUrl;
        a.download = file.fileName || "";
        a.target = "_blank";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (e) {
        this.$message.error("下载失败");
      }
    },
    // 文件预览
    async handleFilePreview(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的预览链接");
        return;
      }
      try {
        let newUrl = '';
        const fileType = this.getFileType(file.fileName);

        if (fileType === 'image') {
          // 图片直接使用fileLinkTransfer
          const res = await fileLinkTransfer(file.downloadUrl);
          newUrl = res.data.url;
        } else if (['pdf', 'word', 'excel', 'ppt'].includes(fileType)) {
          // 文档使用fileLinkLooking
          const res = await fileLinkLooking(file.downloadUrl);
          newUrl = res.data.url;
        } else {
          newUrl = file.downloadUrl;
        }

        if (!newUrl) {
          this.$message.error("获取预览链接失败");
          return;
        }

        this.previewFile = { ...file, downloadUrl: newUrl };
        this.previewDialogVisible = true;
      } catch (e) {
        this.$message.error("预览失败");
      }
    },
    // 获取预览标题
    getPreviewTitle() {
      if (this.previewFile && this.previewFile.fileName) {
        return this.previewFile.fileName;
      }
      return "文件预览";
    }
  }
};
</script>
<style lang="scss" scoped>
.ledger-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.ledger-detail-title {
  font-size: 24px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 24px;
  text-align: center;
  letter-spacing: 2px;
}

.ledger-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 24px 0 12px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
  letter-spacing: 1px;
}

.ledger-row-flex {
  display: flex;
  gap: 32px;
}

.ledger-col-flex {
  flex: 1;
}

.ledger-detail-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 12px;
}

.ledger-detail-table th,
.ledger-detail-table td {
  padding: 6px 12px;
  border-bottom: 1px solid #eaeaea;
}

.ledger-detail-table th.left-align {
  text-align: left;
  background: #f7f7fa;
  width: 120px;
}

.ledger-detail-table td.value {
  color: #333;
}

/* 表格行样式 */
::v-deep .el-table .over-three-days>td {
  background-color: #fff3cd !important;
  /* 黄色背景 */
}

::v-deep .el-table .over-seven-days>td {
  background-color: #f8d7da !important;
  /* 红色背景 */
}

/* 去掉表格鼠标移入时的默认背景变色效果 */
::v-deep .el-table__body tr:hover>td {
  background-color: transparent !important;
}

::v-deep .el-table__body tr.over-three-days:hover>td {
  background-color: #fff3cd !important;
}

::v-deep .el-table__body tr.over-seven-days:hover>td {
  background-color: #f8d7da !important;
}

/* 颜色图例样式 */
.color-legend {
  background-color: #f8f9fa;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.color-legend span {
  display: inline-flex;
  align-items: center;
  margin-right: 20px;
}

.color-legend span:last-child {
  margin-right: 0;
}

// 移除 ledger-detail-* 相关样式，全部用 daily-detail-*
.daily-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.daily-detail-title {
  font-size: 28px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 36px;
  text-align: center;
  letter-spacing: 2px;
}

.daily-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 32px 0 16px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
  letter-spacing: 1px;
}

.daily-row-flex {
  display: flex;
  gap: 32px;
  margin-bottom: 12px;
}

.daily-col-flex {
  flex: 1;
}

.daily-detail-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: none;
}

.daily-detail-table th,
.daily-detail-table td {
  padding: 10px 8px;
  font-size: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.daily-detail-table th {
  width: 120px;
  color: #6b7a90;
  background: none;
  font-weight: normal;
  text-align: right;
  vertical-align: top;
  padding-right: 12px;
}

.daily-detail-table td.value {
  color: #222;
  text-align: left;
  font-weight: 500;
}

.daily-detail-table tr:last-child td,
.daily-detail-table tr:last-child th {
  border-bottom: none;
}

@media (max-width: 900px) {
  .daily-row-flex {
    flex-direction: column;
    gap: 0;
  }
}

@media (max-width: 600px) {
  .daily-detail-title {
    font-size: 20px;
  }

  .daily-section-title {
    font-size: 15px;
    padding-left: 8px;
  }

  .daily-detail-table th,
  .daily-detail-table td {
    font-size: 13px;
    padding: 7px 4px;
  }
}

/* 上传组件样式 */
.upload-container {
  width: 100%;
  overflow: hidden;
  margin-bottom: 10px;
}

.upload-component {
  width: 100%;
}

/* 上传表单项样式 */
.upload-form-item {
  margin-bottom: 20px;
}

.upload-form-item .el-form-item__content {
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 118px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}

::v-deep .upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
}

::v-deep .upload-component .el-upload-list--picture-card {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  margin: 0;
}

/* 确保上传组件在对话框内不会溢出 */
::v-deep .el-dialog__body .upload-container {
  max-width: 100%;
  box-sizing: border-box;
}

/* 统一上传组件样式，避免双重边框 */
::v-deep .upload-component .el-upload-dragger {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
}

::v-deep .upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

/* 调整对话框底部按钮区域的上边距 */
::v-deep .el-dialog__footer {
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 详情弹窗图片展示样式 */
.image-display-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin: 16px 0;
}

.image-item {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.detail-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

/* 文件上传组件样式 */
.file-upload-component {
  width: 100%;
}

.file-upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.file-upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

.file-upload-component .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
  margin-top: 8px;
}

.file-upload-component .el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.file-upload-component .el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

/* 文件列表样式 */
.file-upload-component .el-upload-list--text {
  margin-top: 8px;
}

.file-upload-component .el-upload-list--text .el-upload-list__item {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-name {
  color: #606266;
  font-size: 14px;
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-status-label {
  color: #67c23a;
  font-size: 12px;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-delete {
  color: #f56c6c;
  cursor: pointer;
  font-size: 16px;
}

/* 文件展示区域样式 */
.file-display-container {
  margin: 16px 0;
}

.file-item {
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  transition: all 0.2s;
}

.file-item:hover {
  background: #e9ecef;
  border-color: #409eff;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-info i {
  color: #409eff;
  font-size: 18px;
  margin-right: 8px;
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 14px;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}
</style>
